//
//  ASClassGroupVC.m
//  AvatarShow
//
//  Created by xunruiIOS on 2021/4/30.
//

#import "ASClassGroupVC.h"
#import "ASNoneView.h"
#import "ASHomeApi.h"
#import "ASAvatarGroupCell.h"
#import "ASHomeMainModel.h"
#import "MJRefreshNormalHeader.h"
#import "MJRefreshAutoNormalFooter.h"
#import "ASHomeSearchListVC.h"

@interface ASClassGroupVC () <UITableViewDelegate,UITableViewDataSource>

@property (strong, nonatomic) UITableView *tableView;
@property (assign, nonatomic) NSInteger page;
@property (strong, nonatomic) NSMutableArray *dataArr;
@property (strong, nonatomic) ASNoneView *noneView;
@property (strong, nonatomic) NSMutableArray *collectionArr;        ///已收藏的数组

@end

@implementation ASClassGroupVC

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BACKGROUND_COLOR;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    [self loadCollectionData];
    [self firstLoadData:YES];
    // Do any additional setup after loading the view.
}

#pragma mark - CrateData
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = self.view.backgroundColor;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        [_tableView registerClass:[ASAvatarGroupCell class] forCellReuseIdentifier:ASAvatarGroupCellStr];
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"ASTableCellNoneStr"];
        
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(firstLoadData:)];
        header.lastUpdatedTimeLabel.hidden = YES;
        _tableView.mj_header = header;
        
        MJRefreshAutoNormalFooter *foot = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        [foot endRefreshingWithNoMoreData];
        [foot setTitle:@"" forState:MJRefreshStateNoMoreData];
        _tableView.mj_footer = foot;
    }
    return _tableView;
}

- (ASNoneView *)noneView{
    if (!_noneView) {
        _noneView = [[ASNoneView alloc]initWithFrame:CGRectZero];
        [_noneView.logoImage setImage:[UIImage imageNamed:@"me_wsj"]];
        _noneView.titleLab.text = @"暂时没有相关数据";
    }
    return _noneView;
}

#pragma mark - LoadData
- (void)firstLoadData:(BOOL)ifHUD{
    self.page = 1;
    [self loadMainData:ifHUD];
}

- (void)loadMoreData{
    self.page ++;
    [self loadMainData:NO];
}

- (void)loadMainData:(BOOL)ifHUD{
    if (ifHUD) {
        [MBProgressHUD showMessage:@"加载中..."];
    }
    [ASHomeApi loadOneGroupData:self.subID Completion:^(ASHomeMainModel *  _Nonnull result) {
        [MBProgressHUD hideHUD];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        if (result.state.intValue == 1) {
            [self.dataArr removeAllObjects];
            self.dataArr = [NSMutableArray new];
            if (self.collectionArr.count > 0) {
                for (ASHomeMainModel *subM in self.collectionArr) {
                    if ([subM.tID isEqualToString:result.tID]) {
                        result.is_collect = @"1";
                        break;
                    }
                }
            }
            [self.dataArr addObject:result];
            [self.tableView reloadData];
            if (!result.hasMore) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }else{
            [MBProgressHUD showError:result.errorMsg];
        }
    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:FENETERROR];
    }];
}

///加载收藏的数据
- (void)loadCollectionData{
    self.collectionArr = [NSMutableArray new];
    NSString * temp  = NSTemporaryDirectory();
    NSString * filePath = [temp stringByAppendingPathComponent:COLLECTIONKEY];;
    NSArray *collArr =  [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    [self.collectionArr addObjectsFromArray:collArr];
}


#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.dataArr.count > 0) {
        return self.dataArr.count;
    }
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.dataArr.count > indexPath.row) {
        ASHomeMainModel *subM = self.dataArr[indexPath.row];
        return subM.groupCellH;
    }
    return SCREENH_HEIGHT - Height_NavBar;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.dataArr.count > 0){
        ASAvatarGroupCell *cell = [tableView dequeueReusableCellWithIdentifier:ASAvatarGroupCellStr];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (self.dataArr.count > indexPath.row) {
            cell.model = self.dataArr[indexPath.row];
        }
        @weakify(self);
        cell.labelSelect.clickSubTagBlock = ^(NSString * _Nonnull tagStr) {
            @strongify(self);
            [self pushSearchContent:tagStr];
        };
        
        cell.clickCollectionBlock = ^(ASHomeMainModel * _Nonnull subModel) {
            @strongify(self);
            [self clickCollectionBtn:subModel];
        };
        if (indexPath.row == self.dataArr.count -  1) {
            cell.lineView.hidden = YES;
        }else{
            cell.lineView.hidden = NO;
        }
        return cell;
    }else{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ASTableCellNoneStr"];
        for (UIView *subV in cell.contentView.subviews) {
            if ([subV isKindOfClass:[ASNoneView class]]) {
                [subV removeFromSuperview];
            }
        }
        [cell.contentView addSubview:self.noneView];
        [self.noneView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
        }];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    cell.backgroundColor = [UIColor colorWithHexString:@"ffffff"];
}


///跳转搜索页面
- (void)pushSearchContent:(NSString *)content{
    NSArray *hisArr = [[NSUserDefaults standardUserDefaults]objectForKey:SEARCHHISTORYKEY];
    ASHomeSearchListVC *listVC = [ASHomeSearchListVC new];
    listVC.searchContent = content;
    listVC.historyArr = [NSMutableArray arrayWithArray:hisArr];
    listVC.hasUp = YES;
    listVC.type = 1;
    [self.navigationController pushViewController:listVC animated:YES];
    
    listVC.willBackBlock = ^(NSMutableArray * _Nonnull hisArr) {
        [[NSUserDefaults standardUserDefaults]setObject:[NSArray arrayWithArray:hisArr] forKey:SEARCHHISTORYKEY];
        [[NSUserDefaults standardUserDefaults]synchronize];
    };
}

- (void)clickCollectionBtn:(ASHomeMainModel *)model{
    if (model) {
        if (model.is_collect.integerValue > 0) {
            model.is_collect = @"0";
            [MBProgressHUD showSuccess:@"取消成功"];
            [self addCollectionTongji:@"1" subID:model.tID];
            for (ASHomeMainModel *subM in self.collectionArr) {
                if ([subM.tID isEqualToString:model.tID]) {
                    [self.collectionArr removeObject:subM];
                    break;
                }
            }
        }else{
            model.is_collect = @"1";
            [MBProgressHUD showSuccess:@"收藏成功"];
            [self addCollectionTongji:@"0" subID:model.tID];
            for (int x = 0; x < model.picture_urls.count; x++) {
                ASHomeMainModel *subModel = [ASHomeMainModel new];
                subModel.tID = model.tID;
                subModel.tag_arr = model.tag_arr;
                subModel.picture_urls = model.picture_urls;
                subModel.userid = model.userid;
                subModel.avatar = model.avatar;
                subModel.nickname = model.nickname;
                subModel.is_collect = model.is_collect;
                subModel.descriptionStr = model.descriptionStr;
                subModel.thumb = model.picture_urls[x];
                [self.collectionArr addObject:subModel];
            }
        }
        [self.tableView reloadData];
        
        ///同步收藏的数据
        NSString * temp  = NSTemporaryDirectory();
        NSString * filePath = [temp stringByAppendingPathComponent:COLLECTIONKEY];;
        [NSKeyedArchiver archiveRootObject:self.collectionArr toFile:filePath];
    }
}

///收藏统计
- (void)addCollectionTongji:(NSString *)collectionType subID:(NSString *)sudID{
    [ASHomeApi addCollectionTongji:sudID is_cancel:collectionType completion:^(id  _Nonnull result) {
    } failure:^(NSError * _Nonnull error) {
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
